/*
 *  Created at 2011-01-09 14:32 GMT-03:00
 *  Author: Victor Williams Stafusa da Silva
 *  JSmartUnit
 */
package org.jsmartunit.statement;

import org.jsmartunit.model.TestRunner;

import org.junit.internal.AssumptionViolatedException;
import org.junit.runner.Description;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunNotifier;
import org.junit.runner.notification.StoppedByUserException;
import org.junit.runners.model.Statement;

/**
 * @author Victor Williams Stafusa da Silva
 */
public class NotifyingRunner {

    private NotifyingRunner() {}

    public static Statement notifierFor(final Description description, final RunNotifier notifier, final Statement next) {
        return new Statement() {
            @Override
            public void evaluate() {
                notifier.fireTestStarted(description);
                try {
                    next.evaluate();
                } catch (StoppedByUserException e) {
                    throw e;
                } catch (AssumptionViolatedException e) {
                    notifier.fireTestAssumptionFailed(new Failure(description, e));
                } catch (Throwable e) {
                    notifier.fireTestFailure(new Failure(description, e));
                } finally {
                    notifier.fireTestFinished(description);
                }
            }
        };
    }

    public static Statement notifierFor(final TestRunner runner, final RunNotifier notifier, final Statement next) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                notifierFor(runner.getDescription(), notifier, next).evaluate();
            }
        };
    }
}
